<template>
  <div>
    <BasicTable
      @register="registerTable"
      size="small"
      title="隐患治理记录"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 380px)' }"
      :key="mode"
    >
      <template #toolbar>
        <a-button v-if="mode == 'dispatch'" type="primary" @click="onBatchDispatchButtonClick"
          >批量派单</a-button
        >
      </template>
      <template #title="{ record }">
        <span @click="onTroubleCorrectInfoViewButtonClick(record)">{{ record.title }}</span>
      </template>
      <template #ismajor="{ record }">
        <a-tag :color="record.ismajor ? '#cd201f' : '#3b5999'">{{
          record.ismajor ? '重大' : '一般'
        }}</a-tag>
      </template>
      <template #risklevel="{ record }">
        <a-tag
          v-if="record.risklevel"
          :color="riskLevelOptions.filter((item) => item.value == record.risklevel)[0]?.color"
        >
          {{ riskLevelOptions.filter((item) => item.value == record.risklevel)[0]?.text }}</a-tag
        >
        <span v-else>-</span></template
      >
      <template #unit="{ record }">
        <span @click="onUnitViewButtonClick(record)">{{ record.unit }}</span>
      </template>
      <template #boolSlot="{ record, text, column }">
        <a-tag :color="text == true ? 'red' : 'green'">{{ text == true ? '是' : '否' }}</a-tag>
      </template>
      <!-- 未派单-红色、整改中（已派单整改未完成）-橙色、待验收（整改完成未验收）-黄色、已验收-绿色； -->
      <template #status="{ record, text, column }">
        <a-tag color="red" v-if="!record.hasdispatch">未派单</a-tag>
        <a-tag color="orange" v-else-if="record.hasdispatch && !record.hascorrect">整改中</a-tag>
        <a-tag
          color="yellow"
          v-else-if="record.hasdispatch && record.hascorrect && !record.hascheck"
          >待验收</a-tag
        >
        <a-tag color="green" v-else-if="record.hasdispatch && record.hascorrect && record.hascheck"
          >已验收</a-tag
        >
      </template>
      <template #action="{ column, record }">
        <TableAction
          v-if="mode == 'correct'"
          :actions="[
            {
              label: '整改',
              ifShow: record.hasdispatch === true && record.hascheck === false,
              onClick: onCorrectButtonClick.bind(null, record),
            },
            {
              label: '报告',
              onClick: onRecordButtonClick.bind(null, record),
            },
          ]"
        />
        <TableAction
          v-else-if="mode == 'dispatch'"
          :actions="[
            {
              label: '派单',
              ifShow: record.hasdispatch === false,
              onClick: onDispatchButtonClick.bind(null, record),
            },
            {
              label: '验收',
              ifShow:
                record.hasdispatch === true &&
                record.hascorrect === true &&
                record.hascheck === false,
              onClick: onCheckButtonClick.bind(null, record),
            },
            {
              label: '报告',
              onClick: onRecordButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <UnitBasicInfoDrawer @register="registerUnitBasicInfo" />
    <TroubleDispatchModal @register="registerDispatchModal" @success="afterSuccess" />
    <TroubleCheckModal @register="registerCheckModal" @success="afterSuccess" />
    <TroubleCorrectModal @register="registerCorrectModal" @success="afterSuccess" />
    <TroubleCorrectInfoView @register="registerTroubleCorrectInfoView" />
    <RecordOperateModal @register="registerRecordOperateModal" @success="afterSuccess" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, onMounted, nextTick, h, computed } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { useRouter } from 'vue-router';
  import { Tag, TreeSelect } from 'ant-design-vue';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getUserOrganization } from '/@/api/ehs/organization';
  import { queryTroubleRecordSchema, troubleCorrectRecordColumns } from './troubleCorrect.data';
  import moment from 'moment';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  import { queryEhsTroubleCorrectList, reportEhsTroubleCorrect } from '/@/api/ehs/troublecorrect';
  import TroubleDispatchModal from './troubleDispatchModal.vue';
  import TroubleCheckModal from './TroubleCheckModal.vue';
  import TroubleCorrectModal from './TroubleCorrectModal.vue';
  import UnitBasicInfoDrawer from '../unitDivision/UnitBasicInfoDrawer.vue';
  import TroubleCorrectInfoView from './TroubleCorrectInfoView.vue';
  import { getFileApi } from '/@/api/platform/file';
  import RecordOperateModal from './RecordOperateModal.vue';
  const { globalProjectCode } = useGlobSetting();
  const { uploadUrl } = useGlobSetting();

  export default defineComponent({
    name: 'TroubleIndex',
    components: {
      BasicTable,
      TableAction,
      Tag,
      TroubleDispatchModal,
      TroubleCheckModal,
      TroubleCorrectModal,
      UnitBasicInfoDrawer,
      TroubleCorrectInfoView,
      RecordOperateModal,
    },
    props: ['mode'],
    setup(props, {}) {
      const projectCode = ref<String>(globalProjectCode);
      const organizationCode = ref();
      const router = useRouter();
      const riskLevelOptions = ref('');
      const [registerUnitBasicInfo, { openDrawer: openUnitBasicInfoDrawer }] = useDrawer();
      const [registerTroubleCorrectInfoView, { openDrawer: openTroubleCorrectInfoView }] =
        useDrawer();
      const [registerDispatchModal, { openModal: openDispatchModal }] = useModal();
      const [registerCheckModal, { openModal: openCheckModal }] = useModal();
      const [registerCorrectModal, { openModal: openCorrectModal }] = useModal();
      const [registerRecordOperateModal, { openModal: openRecordOperateModal }] = useModal();
      const [
        registerTable,
        { reload, getForm, getSelectRowKeys, getSelectRows, clearSelectedRowKeys },
      ] = useTable({
        api: queryEhsTroubleCorrectList,
        immediate: false,
        columns: troubleCorrectRecordColumns,
        canResize: true,
        showTableSetting: true,
        tableSetting: {
          redo: false,
        },
        useSearchForm: true,
        formConfig: {
          fieldMapToTime: [['tm', ['begintm', 'endtm'], 'YYYY-MM-DD']],
          labelWidth: 60,
          schemas: queryTroubleRecordSchema,
        },
        beforeFetch: (params) => {
          if (props.mode == 'correct') {
            params.status = '3';
          }
          params.orgcode = organizationCode.value;
        },
        striped: false,
        showIndexColumn: false,
        bordered: true,
        ellipsis: true,
        indentSize: 15,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        rowSelection:
          props.mode == 'dispatch'
            ? {
                type: 'checkbox',
                getCheckboxProps: (record) => ({
                  disabled: record.hasdispatch,
                }),
              }
            : null,
        rowKey: 'correctid',
      });

      function afterSuccess() {
        clearSelectedRowKeys();
        reload();
      }

      // 整改
      function onCorrectButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '隐患治理整改',
          operateString: '填写整改情况',
          dataId: record.correctid,
          title: record.title,
        };
        openCorrectModal(true, propsData);
      }

      // 验收
      function onCheckButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '隐患治理整改',
          operateString: '整改验收',
          title: record.title,
          dataId: record.correctid,
        };
        openCheckModal(true, propsData);
      }

      // 派单
      function onDispatchButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '隐患治理整改',
          operateString: '派单',
          title: record.title,
          dataId: record.correctid,
          unitid: record.unitid,
          type: 1, //派单类型，1：派单，2：批量派单
        };
        openDispatchModal(true, propsData);
      }

      //批量派单
      function onBatchDispatchButtonClick() {
        if (getSelectRowKeys().length == 0) {
          return createMessage.error('请至少选择一条要派单的数据');
        }
        console.log(getSelectRows()[0], 'getSelectRows()[0]');
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '隐患治理整改',
          operateString: getSelectRowKeys().length == 1 ? '派单' : '批量派单',
          ids: getSelectRowKeys(),
          title: getSelectRowKeys().length == 1 ? getSelectRows()[0].title : '',
          unitid: getSelectRowKeys().length == 1 ? getSelectRows()[0].unitid : '',
          type: getSelectRowKeys().length == 1 ? 1 : 2,
        };
        openDispatchModal(true, propsData);
      }

      // 报告
      function onRecordButtonClick(record) {
        if (props.mode == 'dispatch') {
          if (record.rptid <= 0) {
            reportEhsTroubleCorrect(record.correctid).then((res) => {
              window.open(uploadUrl + getFileApi + res.data);
            });
          } else {
            window.open(uploadUrl + getFileApi + record.rptid);
          }
        } else {
          let propsData: QcUnifyTransToChildProps = {
            moduleName: '隐患治理整改',
            operateString: '报告',
            record: record,
          };
          openRecordOperateModal(true, propsData);
        }
      }

      // 单元信息查看Drawer
      function onUnitViewButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '单元基础信息',
          operateType: OperationTypeEnum.VIEW,
          dataId: record.unitid,
        };
        openUnitBasicInfoDrawer(true, propsData);
      }

      // 隐患治理整改信息查看Drawer
      function onTroubleCorrectInfoViewButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '隐患治理整改',
          operateType: OperationTypeEnum.VIEW,
          dataId: record.correctid,
        };
        openTroubleCorrectInfoView(true, propsData);
      }

      onMounted(() => {
        getForm().updateSchema([
          {
            field: 'status',
            show: props.mode != 'correct',
          },
        ]);
        //  获取枚举类
        getUserOrganization(projectCode.value).then((res) => {
          // 请求时需要传入用户的组织编码
          organizationCode.value = res?.orgcode;
          queryUnitDivision({
            includechilds: true,
            isdept: false,
            flagisvalid: false,
            orgcode: res.orgcode,
          }).then((res) => {
            getForm().updateSchema({
              field: 'unitid',
              componentProps: {
                getPopupContainer: (triggerNode) => document.body,
                treeData: res,
                fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
                listHeight: 150,
                treeDefaultExpandAll: true, //默认展开
                showCheckedStrategy: 'SHOW_ALL', //定义选中项回填的方式:默认只显示子节点;SHOW_ALL:显示所有选中节点(包括父节点);SHOW_PARENT:只显示父节点(当父节点下所有子节点都选中时).
              },
            });
          });
          reload();
        });
        queryEnumOptions('EhsRiskLevelEnum').then((res) => {
          // console.log('option res', res);
          if (res != undefined && res != null && res.length > 0x0) {
            riskLevelOptions.value = res[0].options.map((option) => {
              return {
                value: option.key,
                text: option.value,
                color: option.attribute?.split('"')[3],
              };
            });
          }
        });
      });
      return {
        moment,
        organizationCode,
        registerTable,
        router,
        riskLevelOptions,
        afterSuccess,
        onRecordButtonClick,
        onDispatchButtonClick,
        onCheckButtonClick,
        onCorrectButtonClick,
        onBatchDispatchButtonClick,
        registerUnitBasicInfo,
        registerTroubleCorrectInfoView,
        registerDispatchModal,
        registerCheckModal,
        registerCorrectModal,
        registerRecordOperateModal,
        onUnitViewButtonClick,
        onTroubleCorrectInfoViewButtonClick,
      };
    },
  });
</script>

<style scoped>
  a {
    color: #000;
  }
</style>
